package pl.javarsovia.javarsovia4android.sync;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.MenuItem;
import android.widget.Toast;
import pl.javarsovia.R;
import pl.javarsovia.javarsovia4android.activities.MenuActivity;

/**
 * @author mateusz.grzechocinski@gmail.com
 * @since 2010-06-20
 */
public class SyncManager implements DialogInterface.OnClickListener, MenuItem.OnMenuItemClickListener, SyncingThread.OnSyncStatusChangedListener {

	private static final String SYNC_RESULT_MSG_BUNDLE_KEY = "syncResultMsgResId";

	private SyncingThread syncingThread;
	private Activity activity;
	private AlertDialog progressDialog;

	public SyncManager(Activity activity) {
		this.activity = activity;
	}

	@Override
	public boolean onMenuItemClick(MenuItem menuItem) {
		startSyncing();
		return true;
	}

	@Override
	public void onClick(DialogInterface dialogInterface, int i) {
		startSyncing();
	}

	private void startSyncing() {
		syncingThread = new SyncingThread(this, activity);
		syncingThread.start();
		showCancelableProgressDialog();
	}

	private void showCancelableProgressDialog() {
		this.progressDialog = ProgressDialog.show(activity, activity.getString(R.string.sync_title), activity.getString(R.string.label_please_wait), true);
		progressDialog.setCancelable(true);
		progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialogInterface) {
				syncingThread.interrupt();
			}
		});
	}

	@Override
	public void onSyncEnded() {
		sendMsg(R.string.sync_result_ok, null);
	}

	@Override
	public void onSyncError(String errorMsg) {
		sendMsg(R.string.sync_result_error, errorMsg);
	}

	private void sendMsg(int resultMsgId, String errorMsg) {
		Message message = new Message();
		String resultMsg = activity.getString(resultMsgId);
		if (!TextUtils.isEmpty(errorMsg)) {
			resultMsg += ":" + errorMsg;
		}
		message.getData().putString(SYNC_RESULT_MSG_BUNDLE_KEY, resultMsg);
		handler.sendMessage(message);
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			String result = msg.getData().getString(SYNC_RESULT_MSG_BUNDLE_KEY);
			progressDialog.dismiss();
			((MenuActivity) activity).init();
			Toast.makeText(activity, result, Toast.LENGTH_LONG).show();
		}
	};
}

